package com.lsk.netdisk.auth.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class HashUtil {
	public static String clacFileHash(File file){
		try{
			return getHash(file,"SHA-256");
		}catch (Exception e){
			throw new RuntimeException(e);
		}
	}
	private static String getHash(File file, String hashType) throws Exception {
		InputStream fis = new FileInputStream(file);
		byte buffer[] = new byte[1024];
		MessageDigest md5 = MessageDigest.getInstance(hashType);
		for (int numRead = 0; (numRead = fis.read(buffer)) > 0; ) {
			md5.update(buffer, 0, numRead);
		}
		fis.close();
		return toHexString(md5.digest());
	}
	private static String toHexString(byte b[]) {
		StringBuilder sb = new StringBuilder();
		for (byte aB : b) {
			sb.append(Integer.toHexString(aB & 0xFF));
		}
		return sb.toString();
	}
	public static String sha256String(String s){
		try{
			MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
			messageDigest.update(s.getBytes());
			return toHexString(messageDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
}
